package cn.cxion.chat.app.util;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by 13799 on 2018/6/2.
 */

public class StringUtil {

    public static boolean isEmpty(String value) {
        return (value == null) || (value.trim().length() == 0);
    }

    public static boolean istruePhoneNum(String phoneNum) {
        Pattern pattern = Pattern.compile("^[1][345789][0-9]{9}$");
        Matcher matcher = pattern.matcher(phoneNum);
        if (phoneNum == null || "".equals(phoneNum)
                || matcher.matches() == false) {

            return false;
        } else {
            return true;
        }
    }

//    public static String MD5(String password) {
//        return MD5.getMessageDigest(password.getBytes());
//    }

    public static String subZeroAndDot(String s) {
        if (s.indexOf(".") > 0) {
            s = s.replaceAll("0+?$", "");//去掉多余的0
            s = s.replaceAll("[.]$", "");//如最后一位是.则去掉
        }
        if (s.indexOf(".") > 2) {
            if (isDouble(s)) {
                double f = Double.valueOf(s);
                s = String.format("%.2f", f);
            }
        }
        return s;
    }

    public static String subZeroAndDot(double s1) {
        String s = s1 + "";
        if (s.indexOf(".") > 0) {
            s = s.replaceAll("0+?$", "");//去掉多余的0
            s = s.replaceAll("[.]$", "");//如最后一位是.则去掉
        }
        if (s.indexOf(".") > 2) {
            if (isDouble(s)) {
                double f = Double.valueOf(s);
                s = String.format("%.2f", f);
            }
        }
        return s;
    }

    //控制小数点后有几位
    public static String subZeroAndDot(double x, int dig) {
        NumberFormat ddf1 = NumberFormat.getNumberInstance();
        ddf1.setMaximumFractionDigits(dig);
        String str = ddf1.format(x).replace(",", "");
        return str;
    }

    //判断浮点数（double和float）

    public static boolean isDouble(String str) {
        if (null == str || "".equals(str)) {
            return false;
        }
        Pattern pattern = Pattern.compile("^[-\\+]?[.\\d]*$");
        return pattern.matcher(str).matches();

    }


    //解析二维码图片,返回结果封装在Result对象中
//    public static com.google.zxing.Result parseQRcodeBitmap(String bitmapPath) {
//        //解析转换类型UTF-8
//        Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>();
//        hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
//        //获取到待解析的图片
//        BitmapFactory.Options options = new BitmapFactory.Options();
//        //如果我们把inJustDecodeBounds设为true，那么BitmapFactory.decodeFile(String path, Options opt)
//        //并不会真的返回一个Bitmap给你，它仅仅会把它的宽，高取回来给你
//        options.inJustDecodeBounds = true;
//        //此时的bitmap是null，这段代码之后，options.outWidth 和 options.outHeight就是我们想要的宽和高了
//        Bitmap bitmap = BitmapFactory.decodeFile(bitmapPath, options);
//        //我们现在想取出来的图片的边长（二维码图片是正方形的）设置为400像素
//        /**
//         options.outHeight = 400;
//         options.outWidth = 400;
//         options.inJustDecodeBounds = false;
//         bitmap = BitmapFactory.decodeFile(bitmapPath, options);
//         */
//        //以上这种做法，虽然把bitmap限定到了我们要的大小，但是并没有节约内存，如果要节约内存，我们还需要使用inSimpleSize这个属性
//        options.inSampleSize = options.outHeight / 400;
//        if (options.inSampleSize <= 0) {
//            options.inSampleSize = 1; //防止其值小于或等于0
//        }
//        /**
//         * 辅助节约内存设置
//         *
//         * options.inPreferredConfig = Bitmap.Config.ARGB_4444;    // 默认是Bitmap.Config.ARGB_8888
//         * options.inPurgeable = true;
//         * options.inInputShareable = true;
//         */
//        options.inJustDecodeBounds = false;
//        bitmap = BitmapFactory.decodeFile(bitmapPath, options);
//        //新建一个RGBLuminanceSource对象，将bitmap图片传给此对象
//        RGBLuminanceSource rgbLuminanceSource = new RGBLuminanceSource(bitmap);
//        //将图片转换成二进制图片
//        BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(rgbLuminanceSource));
//        //初始化解析对象
//        QRCodeReader reader = new QRCodeReader();
//        //开始解析
//        Result result = null;
//        try {
//            result = reader.decode(binaryBitmap, hints);
//        } catch (Exception e) {
//            // TODO: handle exception
//        }
//
//        return result;
//    }

    /**
     * 获取本地软件版本号名称
     */
    public static String getLocalVersionName(Context ctx) {
        String localVersion = "";
        try {
            PackageInfo packageInfo = ctx.getApplicationContext()
                    .getPackageManager()
                    .getPackageInfo(ctx.getPackageName(), 0);
            localVersion = packageInfo.versionName;

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return localVersion;
    }

    /**
     * 获取本地软件版本号名称
     */
    public static int getLocalVersionCord(Context ctx) {
        int localVersion = 0;
        try {
            PackageInfo packageInfo = ctx.getApplicationContext()
                    .getPackageManager()
                    .getPackageInfo(ctx.getPackageName(), 0);
            localVersion = packageInfo.versionCode;

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return localVersion;
    }

    public static void getTime() {
        //我要获取当前的日期
        Date date = new Date();
        //设置要获取到什么样的时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取String类型的时间
        String createdate = sdf.format(date);
    }

    public static String getDay() {
        //我要获取当前的日期
        Date date = new Date();
        //设置要获取到什么样的时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //获取String类型的时间
        String createdate = sdf.format(date);
        return createdate;
    }

    public static String getTimeHM() {
        //我要获取当前的日期
        Date date = new Date();
        //设置要获取到什么样的时间
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        //获取String类型的时间
        String createdate = sdf.format(date);
        return createdate;
    }

    public static String getTimeH() {
        //我要获取当前的日期
        Date date = new Date();
        //设置要获取到什么样的时间
        SimpleDateFormat sdf = new SimpleDateFormat("HH");
        //获取String类型的时间
        String createdate = sdf.format(date);
        return createdate;
    }

    public static String getTimeM() {
        //我要获取当前的日期
        Date date = new Date();
        //设置要获取到什么样的时间
        SimpleDateFormat sdf = new SimpleDateFormat("mm");
        //获取String类型的时间
        String createdate = sdf.format(date);
        return createdate;
    }

    public static Date str2time(String time) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = sdf.parse(time);
            return date;
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 秒转化为天小时分秒字符串
     *
     * @param seconds
     * @return String
     */

    public static String formatSeconds(long seconds) {

        String timeStr = seconds + "秒";

        if (seconds > 60) {

            long second = seconds % 60;

            long min = seconds / 60;

            timeStr = min + "分" + second + "秒";

            if (min > 60) {

                min = (seconds / 60) % 60;

                long hour = (seconds / 60) / 60;

                timeStr = hour + "小时" + min + "分" + second + "秒";

                if (hour > 24) {

                    hour = ((seconds / 60) / 60) % 24;

                    long day = (((seconds / 60) / 60) / 24);

                    timeStr = day + "天" + hour + "小时" + min + "分" + second + "秒";

                }

            }

        }

        return timeStr;

    }
    //科学计数法转double

    /**
     * BigDecimal的测试，要精确。
     * 还要使得科学计数法的数字，做完全的展示。
     */
    private static void testBigDecimal() {
        Double d = 1.6D;
        //不准确的初始化
        BigDecimal bigDecimal = new BigDecimal(d);
        System.out.println(bigDecimal);

        //使得结果精确的初始化姿势
        bigDecimal = new BigDecimal(d.toString());
        System.out.println(bigDecimal);

        bigDecimal = new BigDecimal("6.214822313132341212666E+18");
        System.out.println(bigDecimal.toPlainString());
    }

    public static boolean isEmail(String email) {
        if (null == email || "".equals(email)) return false;
//        Pattern p = Pattern.compile("\\w+@(\\w+.)+[a-z]{2,3}"); //简单匹配
        Pattern p = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");//复杂匹配
        Matcher m = p.matcher(email);
        return m.matches();
    }

    public static String addZero(int i) {
        String str = "";
        if (i < 10) {
            str = "0" + i;
        } else {
            str = "" + i;
        }
        return str;
    }

    public static String getUUID() {
        UUID uuid = UUID.randomUUID();
        String uniqueId = uuid.toString();
        return uniqueId;

    }
}
